import React from 'react';
import {Table, Input, Button, Popconfirm, Form, Tag} from 'antd';

const EditableContext = React.createContext();
const EditableRow = ({form, index, ...props}) => (
  <EditableContext.Provider value={form}>
    <tr {...props} />
  </EditableContext.Provider>
);

const EditableFormRow = Form.create()(EditableRow);

class EditableCell extends React.Component {
  state = {
    editing: false
  };

  toggleEdit = (e) => {
    const editing = !this.state.editing;
    this.setState({editing}, () => {
      if (editing) {
        this.input.focus();
      }
    });
  };

  save = e => {
    const {record, handleSave} = this.props;
    this.form.validateFields((error, values) => {
      if (error && error[e.currentTarget.id]) {
        return;
      }
      this.toggleEdit();
      handleSave({...record, ...values});
    });
  };

  renderCell = form => {
    this.form = form;
    const {children, dataIndex, record, title} = this.props;
    const {editing} = this.state;
    return editing ? (
      <Form.Item style={{margin: 0}}>
        {form.getFieldDecorator(dataIndex, {
          rules: [
            {
              required: true,
              message: `${title} is required.`
            }
          ],
          initialValue: record[dataIndex]
        })(<Input ref={node => (this.input = node)} onPressEnter={this.save} onBlur={this.save}/>)}
      </Form.Item>
    ) : (
      <div
        className="editable-cell-value-wrap"
        style={{paddingRight: 24}}
        onClick={this.toggleEdit}
      >
        {children}
      </div>
    );
  };

  render() {
    const {
      editable,
      dataIndex,
      title,
      record,
      index,
      handleSave,
      children,
      ...restProps
    } = this.props;
    return (
      <td {...restProps}>
        {editable ? (
          <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>
        ) : (
          children
        )}
      </td>
    );
  }
}

class EditableTable extends React.Component {

  constructor(props) {
    super(props);
    this.columns = [
      {
        title: '快递名称',
        dataIndex: 'express_type',
        editable: true
      },
      {
        title: '运单号',
        dataIndex: 'express_no',
        editable: true
      },
      {
        title: '商品名称',
        dataIndex: 'goods_title',
        editable: true
      },
      {
        title: '数量',
        dataIndex: 'num',
        editable: true
      },
      {
        title: '操作',
        dataIndex: 'operation',
        render: (text, record) =>
          this.state.dataSource.length >= 1 ? (
            <Popconfirm title="Sure to delete?" onConfirm={() => this.handleDelete(record.key)}>
              <a>删 除</a>
            </Popconfirm>
          ) : null
      }
    ];

    this.state = {
      dataSource: [
        {
          key: '0',
          express_no: '运单号',
          goods_title: '商品名称',
          num: '数量',
          express_type: '快递名称'
        }
      ],
      count: 1,
      express: null
    };
  }

  componentDidMount() {
    const dataSource = this.props.data.map(item => {
      return {
        key: '' + item.goods_id,
        express_no: '运单号',
        express_type: '快递',
        goods_title: item.goods_title,
        num: item.number,
        supplier_id: item.supplier_id,
        order_no: item.order_no
      };
    });
    this.setState({dataSource});
  }

  handleDelete = key => {
    const dataSource = [...this.state.dataSource];
    this.setState({dataSource: dataSource.filter(item => item.key !== key)});
  };

  // 可以获取这个值 表单的值
  onChange = value => {
    this.setState({
      express: value
    });
  };

  handleAdd = () => {
    const {count, dataSource} = this.state;
    const newData = {
      key: count,
      express_no: `运单号`,
      goods_title: '商品名称',
      num: `数量`,
      express_type: '快递名称'
    };
    this.setState({
      dataSource: [...dataSource, newData],
      count: count + 1
    });
  };

  handleSave = row => {
    const newData = [...this.state.dataSource];
    const index = newData.findIndex(item => row.key === item.key);
    const item = newData[index];
    newData.splice(index, 1, {
      ...item,
      ...row
    });
    this.setState({dataSource: newData});
  };

  render() {
    const {dataSource} = this.state;
    const components = {
      body: {
        row: EditableFormRow,
        cell: EditableCell
      }
    };
    const columns = this.columns.map(col => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          editable: col.editable,
          dataIndex: col.dataIndex,
          title: col.title,
          handleSave: this.handleSave
        })
      };
    });

    this.props.collectingData(this.state.express, this.state.dataSource);

    return (
      <div>
        {/* this.props.logisticsTemplate */}
        <Button onClick={this.handleAdd} type="primary" style={{marginBottom: 16, marginLeft: 20}} size={'small'}>
          添加行
        </Button>
        <Tag color="#f50" style={{marginLeft: '20px'}}>商品总数：{this.props.tempNum}</Tag>
        <span style={{marginLeft: '100px', fontWeight: 'bold'}}>可发快递选择项：</span>
        {
          this.props.logisticsTemplate.map(item => {
            return <Tag color="#f50" style={{marginLeft: '20px'}}>{item.template_name}</Tag>;
          })
        }
        <Table
          components={components}
          rowClassName={() => 'editable-row'}
          bordered
          dataSource={dataSource}
          columns={columns}
          pagination={false}
        />
      </div>
    );
  }
}


export default EditableTable;
